import React from "react";
import {useSelector, useStore, useDispatch } from 'react-redux'
import { toggleTodo } from "../redux/actions";
import cx from "classnames";

import { VISIBILITY_FILTERS } from "./constants";

export default function TodoList(props) {
  
  const store = useStore()
  const dispatch = useDispatch()

  const visibilityFilter = useSelector(state => state.visibilityFilter)

  const allIds = useSelector(state => state.todos.allIds)
  const byIds = useSelector(state => state.todos.byIds)
  
  function getTodosByVisibilityFilter(todos) {

    let state = store.getState()
    console.log("todo-- ", state);
    
    let allTodos = todos.map( (id) => {
      return { ...byIds[id], id }
    })

    switch (visibilityFilter) {
      case VISIBILITY_FILTERS.COMPLETED:
        return allTodos.filter(todo => todo.completed);
      case VISIBILITY_FILTERS.INCOMPLETE:
        return allTodos.filter(todo => !todo.completed);
      case VISIBILITY_FILTERS.ALL:
      default:
        return allTodos;
    }

  }

  const handleClick = (todoId) => {
    console.log("id " + todoId);

    dispatch(toggleTodo(todoId))

    console.log("info " + JSON.stringify(byIds[todoId]));
    
  }

  const Todo =  (props) => {
    
    let { todo } = props

    return (
      <li className="todo-item" onClick={() => handleClick(todo.id)}>
        {todo && todo.completed ? "👌" : "👋"}{" "}
        <span
          className={cx(
            "todo-item__text",
            todo && todo.completed && "todo-item__text--completed"
          )}
        >
          {todo.content}
        </span>
      </li>
    )  

  }

  return (

    <div>
      
      <ul className="mx-4">
        {allIds && allIds.length
          ? getTodosByVisibilityFilter(allIds).map((todo, index) => {
              return <Todo key={`todo-${todo.id}`} todo={todo} />;
            })
          : "No todos, yay!"}
      </ul>

    </div>
    
  )
  
}
